<?php

namespace App\Service\Invoice;

use App\Enums\OpenShop\InvestmentPromotion\UserContractEnum;
use App\Http\Resources\Invoice\AppInvoiceHistoryListResource;
use App\Models\BaseModel;
use App\Models\Common\ConfigModel;
use App\Models\Invoice\InvoiceHeadModel;
use App\Library\FeiShu\SendFs;
use App\Models\Invoice\InvoiceHistoryBusinessRelModel;
use App\Models\Invoice\InvoiceHistoryModel;
use App\Models\OpenShop\InvestmentPromotion\OpenShopMainProcessModel;
use App\Models\Shop\ShopModel;
use App\Models\OpenShop\InvestmentPromotion\OpenShopSignOrderModel;
use App\Models\OpenShop\InvestmentPromotion\OpenShopUserContractModel;
use App\Remote\MoreDo\InvoiceRemote;
use App\Remote\Rms\RmsShopRemote;
use App\Service\Common\EmailV2Service;
use App\Service\Common\FileService;
use App\Service\Common\SmsService;
use App\Service\Invoice\Merchant\InvoiceHeaderService;
use Exception;
use GuzzleHttp\Exception\GuzzleException;
use Illuminate\Support\Carbon;
use Illuminate\Support\Facades\DB;
use Illuminate\Support\Facades\File;
use Illuminate\Support\Str;
use Illuminate\Validation\ValidationException;
use Illuminate\View\Compilers\BladeCompiler;
use Kuafu\Snow\KfSnow;
use Psr\Container\ContainerExceptionInterface;
use Psr\Container\NotFoundExceptionInterface;

class InvoiceService
{
    /**
     * 申请开票
     *
     * @param object $params
     * @param int $shopId
     * @param int $uid
     * @throws GuzzleException
     * @throws ValidationException
     */
    public static function applyInvoice(object $params, int $shopId, int $uid)
    {
        try {
            //todo 更新抬头信息
            InvoiceHeaderService::update(array_merge((array)$params,
                ["id" => $params->invoiceHeaderId, "shopId" => $shopId, "userId" => $uid]));
        } catch (Exception $exception) {
            logException("抬头更新失败", $exception, null, true, true);
        }


        //todo 获取orm订单数据
        $detailsCollect = collect(\App\Remote\Orm\InvoiceRemote::previewInvoice(
            collect($params->businessRel)->pluck("businessId")->toArray()
        )["lists"]);

        $businessRelCollect = collect($params->businessRel);
        $shopModel          = ShopModel::query()->where("id", $shopId)->first();
        $remark             = "";
        if ($shopModel) {
            $remark = vsprintf("%s %s %s", [
                $shopModel->shopCode,
                $shopModel->name,
                $businessRelCollect->pluck("businessOrderTime")->map(function ($orderTime) {
                    return Carbon::createFromTimestamp(strtotime($orderTime))->format("Y.m");
                })->unique()->values()->implode(" ")
            ]);
        }

        try {
            DB::beginTransaction();

            // 开票记录表写入
            $invoiceId = InvoiceHistoryModel::query()->insertGetId(array_merge(collect((array)$params)
                ->except(["businessDetails", "businessRel", "invoiceHeaderId"])->toArray(), [
                "shopId"                => $shopId,
                "channel"               => InvoiceHistoryModel::CHANNEL_AUTO,
                "orderId"               => KfSnow::nextIdCache(),
                "status"                => InvoiceHistoryModel::STATUS_1,
                "invoiceTotalAmount"    => (string)$detailsCollect->pluck("total_price")->sum(),
                "invoiceTaxTotalAmount" => (string)$detailsCollect->pluck("tax_price")->sum(),
                "businessDetails"       => $detailsCollect->toJson(JSON_UNESCAPED_UNICODE),
                "remark"                => $remark,
                "createdAt"             => time(),
                "updatedAt"             => time(),
                "createdByUid"          => $uid,
                "updatedByUid"          => $uid
            ]));

            //开票业务关联表写入
            InvoiceHistoryBusinessRelModel::query()->insert(
                $businessRelCollect->map(function ($row) use ($invoiceId, $uid) {
                    return [
                        "businessId"         => $row["businessId"] ?? "",
                        "invoiceTotalAmount" => $row["invoiceTotalAmount"],
                        "businessOrderTime"  => strtotime($row["businessOrderTime"]),
                        "invoiceHistoryId"   => $invoiceId,
                        "createdAt"          => time(),
                        "createdByUid"       => $uid,
                        "updatedByUid"       => $uid
                    ];
                })->values()->toArray());
            DB::commit();
        } catch (Exception $exception) {
            DB::rollBack();
            throw $exception;
        }

        //同步orm开票id
        self::syncOrmOrderInvoiceId(
            $businessRelCollect->pluck("businessId")->toArray(),
            $invoiceId
        );

        //同步orm开票状态
        self::syncOrmOrderInvoiceStatus($invoiceId, InvoiceHistoryModel::STATUS_1);
    }

    /**
     * app - 数字红票
     *
     * @param object $params
     * @param int $uid
     * @throws GuzzleException
     */
    public static function appReApplyInvoice(object $params, int $uid)
    {
        $invoiceHistoryModel = InvoiceHistoryModel::query()->where("id", $params->id)->first();
        $businessRel         = InvoiceHistoryBusinessRelModel::query()
                                                             ->where("invoiceHistoryId", $params->id)
                                                             ->get();

        //新开蓝票基础数据写入
        try {
            DB::beginTransaction();
            //开票记录表写入
            $invoiceId = InvoiceHistoryModel::query()->insertGetId(array_merge(collect((array)$params)
                ->except(["id"])->toArray(), [
                "channel"               => InvoiceHistoryModel::CHANNEL_AUTO,
                "businessDetails"       => $invoiceHistoryModel->businessDetails,
                "remark"                => $invoiceHistoryModel->remark,
                "orderId"               => KfSnow::nextIdCache(),
                "shopId"                => $invoiceHistoryModel->shopId,
                "invoiceTotalAmount"    => $invoiceHistoryModel->invoiceTotalAmount,
                "invoiceTaxTotalAmount" => $invoiceHistoryModel->invoiceTaxTotalAmount,
                "createdAt"             => time(),
                "updatedAt"             => time(),
                "createdByUid"          => $uid,
                "updatedByUid"          => $uid
            ]));

            //开票业务关联表写入
            InvoiceHistoryBusinessRelModel::query()->insert($businessRel->map(function (
                InvoiceHistoryBusinessRelModel $historyBusinessRelModel
            ) use ($invoiceId, $uid) {
                return [
                    "businessId"         => $historyBusinessRelModel->businessId,
                    "businessOrderTime"  => $historyBusinessRelModel->businessOrderTime,
                    "invoiceTotalAmount" => $historyBusinessRelModel->invoiceTotalAmount,
                    "invoiceHistoryId"   => $invoiceId,
                    "createdAt"          => time(),
                    "createdByUid"       => $uid,
                    "updatedByUid"       => $uid
                ];
            })->values()->toArray());

            DB::commit();
        } catch (Exception $exception) {
            DB::rollBack();
            throw $exception;
        }

        //原蓝票变更为红冲中
        $invoiceHistoryModel->setRawAttributes([
            "newInvoiceId" => $invoiceId,
            "status"       => InvoiceHistoryModel::STATUS_4,
            "updatedAt"    => time(),
            "updatedByUid" => request()->user()->id
        ])->save();

        //同步orm开票状态
        self::syncOrmOrderInvoiceStatus($invoiceId, InvoiceHistoryModel::STATUS_4);
    }

    /**
     * 调起开票
     *
     * @param int $invoiceId
     * @return mixed
     * @throws GuzzleException
     * @throws ValidationException
     */
    public static function invoice(int $invoiceId)
    {
        $invoiceHistoryModel = InvoiceHistoryModel::query()->where("id", $invoiceId)->first();
        $details             = jsonToArr($invoiceHistoryModel->businessDetails, []);

        return InvoiceRemote::applyInvoice(
            $invoiceHistoryModel->orderId,
            InvoiceRemote::renderTemplate($invoiceHistoryModel, $details)
        );
    }

    /**
     * web端发起红冲
     *
     * @param object $params
     * @throws GuzzleException
     * @throws Exception
     */
    public static function webRedInvoice(object $params)
    {
        $invoiceHistoryModel = InvoiceHistoryModel::query()->where("id", $params->invoiceId)->first();

        //原蓝票变更为红冲中
        $invoiceHistoryModel->setRawAttributes([
            "status"       => InvoiceHistoryModel::STATUS_4,
            "updatedAt"    => time(),
            "updatedByUid" => request()->user()->id
        ])->save();

        //同步orm开票状态
        self::syncOrmOrderInvoiceStatus($params->invoiceId, InvoiceHistoryModel::STATUS_4);
    }

    /**
     * 回调
     *
     * @param object $params
     * @throws ContainerExceptionInterface
     * @throws NotFoundExceptionInterface
     * @throws Exception|GuzzleException
     */
    public static function notify(object $params)
    {
        try {
            //解析票据xml数据
            $decode         = base64_decode(attributeGet($params, "data.0.fpData", ""));
            $iconv          = iconv("GB2312", "UTF-8//IGNORE", $decode);
            $replace        = str_replace("GBK", "UTF-8", $iconv);
            $xmlString      = simplexml_load_string($replace, 'SimpleXMLElement', LIBXML_NOCDATA);
            $fpData         = json_decode(json_encode($xmlString), true);
            $invoiceDetails = json_encode($fpData, JSON_UNESCAPED_UNICODE);

            //pdf票据转存
            $originalInvoiceFile = attributeGet($params, "data.0.pdf", "");
            $ossInvoiceFile      = FileService::transferred($originalInvoiceFile, vsprintf("%s.%s", [
                md5($originalInvoiceFile),
                explode("?", File::extension($originalInvoiceFile))[0]
            ]), "invoice");

            //判断红蓝票
            $isRedInvoice        = Str::startsWith($params->orderId, "hc-");
            $actuallyOrderId     = str_replace("hc-", "", $params->orderId);
            $invoiceHistoryModel = InvoiceHistoryModel::query()->where("orderId", $actuallyOrderId)->first();
            $businessRel         = $invoiceHistoryModel->businessRel;

            $oldInvoiceId      = $invoiceHistoryModel->id;
            $newInvoiceId      = $invoiceHistoryModel->newInvoiceId;
            $businessType      = $invoiceHistoryModel->businessType;
            $mobile            = $invoiceHistoryModel->mobile;
            $email             = $invoiceHistoryModel->email;
            $shopId            = $invoiceHistoryModel->shopId;
            $blueInvoiceNumber = $invoiceHistoryModel->blueInvoiceNumber;
            if ($isRedInvoice) {
                //todo 红冲业务逻辑处理
                $invoiceHistoryModel->setRawAttributes([
                    "errorMsg"          => "",
                    "redInvoiceFile"    => $originalInvoiceFile,
                    "status"            => InvoiceHistoryModel::STATUS_5,
                    "redInvoiceOssFile" => $ossInvoiceFile,
                    "redInvoiceDetails" => $invoiceDetails,
                    "updatedAt"         => time()
                ])->save();

                //红冲成功飞书消息推送
                try {
                    Web\InvoiceService::sendFs($oldInvoiceId, InvoiceHistoryModel::FS_NOTICE_STATUS_3);// 发票成功/失败 飞书通知
                } catch (Exception $exception) {
                    logException("红冲成功 - 飞书消息发送失败【{$oldInvoiceId}】", $exception, (array)$params, true,
                        true);
                }

                //同步orm开票状态 -》 变为待提交
                self::syncOrmOrderInvoiceStatus($oldInvoiceId, 0);

                if ($newInvoiceId > 0) {
                    //todo 开具新蓝票
                    $newInvoiceHistoryModel = InvoiceHistoryModel::query()->where("id", $newInvoiceId)->first();
                    $newInvoiceHistoryModel->setRawAttributes([
                        "status"    => InvoiceHistoryModel::STATUS_1,
                        "updatedAt" => time()
                    ])->save();

                    //同步orm 新开蓝票开票id
                    self::syncOrmOrderInvoiceId(
                        $businessRel->pluck("businessId")->toArray(),
                        $newInvoiceId
                    );

                    //同步orm开票状态
                    self::syncOrmOrderInvoiceStatus($newInvoiceId, InvoiceHistoryModel::STATUS_1);
                }
            } else {
                //todo 蓝票开票逻辑处理
                $invoiceHistoryModel->setRawAttributes([
                    "blueInvoiceFile"    => $originalInvoiceFile,
                    "status"             => InvoiceHistoryModel::STATUS_3,
                    "errorMsg"           => "",
                    "blueInvoiceOssFile" => $ossInvoiceFile,
                    "blueInvoiceDetails" => $invoiceDetails,
                    "updatedAt"          => time()
                ])->save();

                //同步orm开票状态
                self::syncOrmOrderInvoiceStatus($oldInvoiceId, InvoiceHistoryModel::STATUS_3);

                //开票成功飞书消息推送
                try {
                    Web\InvoiceService::sendFs($oldInvoiceId, InvoiceHistoryModel::FS_NOTICE_STATUS_1);// 发票成功/失败 飞书通知
                } catch (Exception $exception) {
                    logException("蓝票开票成功 飞书消息发送失败 [{$oldInvoiceId}]", $exception, (array)$params, true,
                        true);
                }

                try {
                    //todo 邮件发送 @超人
                    self::transmitEmail($oldInvoiceId, $shopId, $email);
                } catch (Exception $exception) {
                    logException("邮件发送失败", $exception, (array)$params, true, true);
                }

                try {
                    //todo 短信发送
                    if ($mobile) {
                        switch ($businessType) {
                            case InvoiceHistoryModel::BUSINESS_TYPE_1:
                                $template = config('sms.template.invoiceOrmOrder');
                                (new SmsService())->aliyunSend($mobile, $template, [
                                    "invoiceCode" => $blueInvoiceNumber
                                ]);
                                break;
                            case InvoiceHistoryModel::BUSINESS_TYPE_2:
                                $template = config('sms.template.invoiceSoftOrder');
                                (new SmsService())->aliyunSend($mobile, $template, [
                                    "invoiceCode" => $blueInvoiceNumber
                                ]);
                                break;
                        }
                    }
                } catch (Exception $exception) {
                    logException("短信发送失败", $exception, (array)$params, true, true);
                }
            }
        } catch (Exception $exception) {
            logException("票据回调失败: {$exception->getMessage()}", $exception, (array)$params, true, true,
                SendFs::ROBOT_WARNING);
            throw new Exception("票据回调失败");
        }
    }

    /**
     * 商家端列表
     *
     * @param object $params
     * @param int $shopId
     * @return array
     */
    public static function list(object $params, int $shopId): array
    {
        $paginate = InvoiceHistoryModel::query()
                                       ->when(checkFieldLen($params, "businessType"), function ($query) use ($params) {
                                           $query->where("businessType", $params->businessType);
                                       })
                                       ->where("shopId", $shopId)
                                       ->where("status", ">", 0)
                                       ->orderBy("id", "desc")
                                       ->paginate($params->pageSize, ['*'], 'pageNum',
                                           $params->pageNum);

        return [
            "list"     => AppInvoiceHistoryListResource::collection($paginate->items()),
            "count"    => $paginate->total(),
            "pageNum"  => $params->pageNum,
            "pageSize" => $params->pageSize
        ];
    }

    /**
     * 商家端发票详情
     * @param object $params
     * @param int $shopId
     * @return array
     */
    public static function info(int $id, int $shopId): array
    {
        $info            = InvoiceHistoryModel::query()
                                              ->select("id", "headerType", 'businessType', "invoiceType",
                                                  "invoiceTitle",
                                                  "companyTaxNumber", "companyRegisterAddress", "companyRegisterMobile",
                                                  "companyDepositBank", "companyDepositBankNum", "mobile", "email",
                                                  "status",
                                                  "invoiceTotalAmount", "blueInvoiceTime", "blueInvoiceOssFile",
                                                  "redInvoiceOssFile", "invoiceTaxTotalAmount")
                                              ->where("shopId", $shopId)
                                              ->where("id", $id)
                                              ->first();
        $orderInfo       = [];
        $isAllowExchange = false;
        if (!empty($info)) {

            // 查询是否有换开记录
            $exchangeLog = InvoiceHistoryModel::query()->where("newInvoiceId", $id)->first();
            if (is_null($exchangeLog) && $info['status'] == InvoiceHistoryModel::STATUS_3 && (time() - $info['blueInvoiceTime']) < 93 * 86400) {

                // 无换开记录，已开蓝票， 开票时间在三个月内(93天)
                $isAllowExchange = true;
            }

            // 开票方目前写死
            $info["invoiceParty"]    = "厦门万皮思供应链管理有限公司";
            $info['blueInvoiceTime'] = date("Y-m-d", $info['blueInvoiceTime']);

            // 订单信息
            $orderInfo = InvoiceHistoryBusinessRelModel::query()
                                                       ->where("invoiceHistoryId", $info['id'])
                                                       ->select("invoiceTotalAmount", "businessId", "businessOrderTime")
                                                       ->get();
            if (!empty($orderInfo)) {
                foreach ($orderInfo as $k => $item) {
                    $orderInfo[$k]['businessOrderTime'] = date("Y-m-d H:i:s", $item['businessOrderTime']);
                }
            }


        }
        return [
            'isAllowExchange' => $isAllowExchange,
            "info"            => $info,
            'orderInfo'       => $orderInfo,
        ];
    }

    /**
     * 同步门店发票抬头
     *
     * @param int $shopId
     * @return array
     * @throws GuzzleException
     */
    public static function syncInvoiceHeader(int $shopId, int $userId): array
    {
        // 获取shopInfo
        $shopList = RmsShopRemote::getShopInfoByIds([$shopId],['id,shopCode,shopMobile']);
        if (empty($shopList['shopList'][0])) {
            return [false, "门店不存在"];
        }
        $shopInfo = $shopList['shopList'][0];
        $shopCode   = $shopInfo['shopCode'] ?? '';
        $shopMobile = $shopInfo['shopMobile'] ?? 0;
        if (empty($shopCode)) {
            return [false, "shopCode 异常"];
        }

        // 查询最近一笔签约完成的订单
        $signOrderInfo = OpenShopMainProcessModel::query()
            ->where('shopId', $shopId)
            ->where('childLocationOrder', 0)
            ->first();

        // 签约订单不存在/合同不存在/非公司抬头   采用个人抬头
        $headerType             = InvoiceHeadModel::HEADER_TYPE_PERSON;
        $invoiceTitle           = '个人';
        $companyTaxNumber       = '';
        $companyRegisterAddress = '';
        if (!empty($signOrderInfo->id)) {
            // 合同变更, 一笔订单会有多笔合同记录
            // 直接查询公司的抬头, 不限制状态
            $contractInfo = OpenShopUserContractModel::query()
                                                     ->where("orderNo", $signOrderInfo->orderNo)
                                                     ->where('contractors', UserContractEnum::CONTRACT_COMPANY)
                                                     ->orderByDesc("createdAt")
                                                     ->first();

            // 合同为准
            if (!empty($contractInfo)) {
                $headerType             = InvoiceHeadModel::HEADER_TYPE_COMPANY;
                $invoiceTitle           = $contractInfo->companyName;
                $companyTaxNumber       = $contractInfo->businessLicenseNumber;
                $companyRegisterAddress = $contractInfo->address;
            }
        }

        // 开始同步
        $invoiceInfo                        = InvoiceHeadModel::query()->where('shopId', $shopId)->first();
        $dealData['headerType']             = $headerType;
        $dealData['invoiceTitle']           = $invoiceTitle;
        $dealData['companyTaxNumber']       = $companyTaxNumber;
        $dealData['companyRegisterAddress'] = $companyRegisterAddress;

        if (!empty($invoiceInfo)) {

            // 更新
            if ($headerType == InvoiceHeadModel::HEADER_TYPE_PERSON) {
                $dealData['invoiceType'] = InvoiceHeadModel::INVOICE_TYPE_COMMON;
            }

            $dealData['updatedAt']    = time();
            $dealData['updatedByUid'] = $userId;
            InvoiceHeadModel::query()->where('shopId', $shopId)->update($dealData);

        } else {

            // 插入
            $dealData['invoiceType']           = InvoiceHeadModel::INVOICE_TYPE_COMMON;
            $dealData['shopId']                = $shopId;
            $dealData['merchantUserId']        = $userId;
            $dealData['companyRegisterMobile'] = '';
            $dealData['companyDepositBank']    = '';
            $dealData['companyDepositBankNum'] = '';
            $dealData['email']                 = '';
            $dealData['mobile']                = $shopMobile;
            $dealData['invoiceDefault']        = BaseModel::DEFAULT_YES;
            $dealData['createdAt']             = time();
            $dealData['createdByUid']          = $userId;
            InvoiceHeadModel::query()->where('shopId', $shopId)->insert($dealData);
        }
        return [true, "success"];
    }

    /**
     * @param int $invoiceId
     * @param int $status
     * @throws GuzzleException
     * @throws Exception
     */
    public static function syncOrmOrderInvoiceStatus(int $invoiceId, int $status)
    {
        try {
            //同步orm开票状态
            \App\Remote\Orm\InvoiceRemote::syncOrderInvoiceStatus($invoiceId, $status);
        } catch (Exception $exception) {
            logException("orm 订货订单开票状态同步失败", $exception, compact("invoiceId", "status"), true, false);
        }
    }

    /**
     * @param array $orders
     * @param int $invoiceId
     * @throws GuzzleException
     * @throws Exception
     */
    public static function syncOrmOrderInvoiceId(array $orders, int $invoiceId)
    {
        try {
            //同步orm开票状态
            \App\Remote\Orm\InvoiceRemote::syncOrderInvoiceId($orders, $invoiceId);
        } catch (Exception $exception) {
            logException("orm 订货订单开票ID失败", $exception, compact("invoiceId", "orders"), true, false);
        }

    }

    /** 发票邮件转发
     * @param int $id
     * @param int $shopId
     * @param string $receiveEmail
     * @return  array
     */
    public static function transmitEmail(int $id, int $shopId, string $receiveEmail): array
    {
        if ($receiveEmail == "") {
            return [false, "邮件信息错误"];
        }

        // 查询开票数据
        $invoiceInfo = InvoiceHistoryModel::query()
                                          ->where('id', $id)
                                          ->where("shopId", $shopId)
                                          ->first();

        if (empty($invoiceInfo->id) || $invoiceInfo->status != InvoiceHistoryModel::STATUS_3) {
            return [false, "开票信息异常"];
        }

        $invoiceNumber = $invoiceInfo->blueInvoiceNumber;
        $receiveName   = $invoiceInfo->invoiceTitle;
        $invoicePdfUrl = $invoiceInfo->blueInvoiceOssFile;

        // 下载到本地
        $temFilePath = storage_path("/app/public/" . time() . mt_rand(1, 9999) . ".pdf");
        file_put_contents($temFilePath, file_get_contents($invoicePdfUrl));

        $invoiceShowFileName = '电子发票.pdf';
        switch ($invoiceInfo->businessType) {
            case InvoiceHistoryModel::BUSINESS_TYPE_1:
                $invoiceShowFileName = InvoiceHistoryModel::BUSINESS_TYPE_TEXT[InvoiceHistoryModel::BUSINESS_TYPE_1] . $invoiceShowFileName;
                break;
            case InvoiceHistoryModel::BUSINESS_TYPE_2:
                $invoiceShowFileName = InvoiceHistoryModel::BUSINESS_TYPE_TEXT[InvoiceHistoryModel::BUSINESS_TYPE_2] . $invoiceShowFileName;
                break;
        }

        $title = "【电子发票】您收到一张【厦门万皮思供应链有限公司】开具的发票【发票号码：" . $invoiceNumber . "】";

        $headerName   = $invoiceInfo['invoiceType'] == 1 ? "专用发票" : "普通发票";
        $invoiceData  = date("Y年m月d日", $invoiceInfo['blueInvoiceTime']);
        $invoiceMoney = $invoiceInfo['blueTaxValueTotal'];

        $otherFileData = [
            [
                'url'  => $temFilePath,
                'name' => $invoiceShowFileName,
            ],
        ];

        $body = BladeCompiler::render(
            file_get_contents(resource_path("/Invoice/InvoiceTransmitEmailTemplate.html")), [
            "invoiceInfo"         => $invoiceInfo,
            "headerName"          => $headerName,
            "invoiceData"         => $invoiceData,
            "invoiceMoney"        => $invoiceMoney,
            "invoicePdfUrl"       => $invoicePdfUrl,
            "invoiceShowFileName" => $invoiceShowFileName
        ]);

        // 获取配置
        $config = ConfigModel::getOrderGoodsEmailConfig();
        list($sendStatus, $sendMsg) = (new EmailV2Service($config))->sendEmail($receiveEmail, $receiveName, $title, $body,  $otherFileData);
        unlink($temFilePath);
        return [$sendStatus, $sendMsg];
    }

}
